package com.tnsw.noxnox.streamer;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;

import com.tnsw.noxnox.db.DBManager;
import com.tnsw.noxnox.db.tables.DownloadProgress;

import android.content.Context;
import android.net.Uri;
import android.util.Log;

public class MediaHandler implements HttpRequestHandler {

	private String tag = "MediaHandler";
	private Context context;
	private DBManager dbm;
	
	public MediaHandler(Context context) {
		Log.d(tag, "Constructor()");
		this.context = context;
		this.dbm = DBManager.getInstance(context);
	}
	
	@Override
	public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
		Log.d(tag, "handle() ..");
		String uriStr = request.getRequestLine().getUri();
		String method = request.getRequestLine().getMethod();
		
		Uri uri = Uri.parse(uriStr);
		String lastPath = uri.getLastPathSegment();
		String id = uri.getQueryParameter("id");
		
		Log.d(tag, "uri=" + uriStr + ", method=" + method + ", lastPath=" + lastPath + ", id=" + id);
		
		if (lastPath.equals("play")) {
			this.handlePlay(request, response, context);
		}
	}
	
	public static int[] getRanges(String range, int lastByte) {
		int[] result = new int[2];  // [0]=being, [1]=end
		result[0] = -1;
		result[1] = -1;
		
		String s1[] = range.split("=");
		if (s1[0].toLowerCase().equals("bytes")) {
			String s2[] = s1[1].split("-");
			result[0] = Integer.valueOf(s2[0]);
			if (s2.length == 1) {
				result[1] = lastByte;
			} else {
				result[1] = Integer.valueOf(s2[1]);
			}
		}
		
		return(result);
	}
	
	private void handlePlay(HttpRequest request, HttpResponse response, HttpContext context) {
		Uri uri = Uri.parse(request.getRequestLine().getUri());

		String id = uri.getQueryParameter("id");
		ArrayList<DownloadProgress> aDp = this.dbm.getDownloadProgress("primarykey=?", new String[] {id}, "");
		if (aDp != null) {
			DownloadProgress dp = aDp.get(0);
			String contentType = this.dbm.getDownloadAttributeValue(dp.primarykey, "content-type");
			Log.d(tag, "found id=" + id + ", file=" + dp.filename);
			try {
				FileInputStream fs = new FileInputStream(dp.filename);
				InputStreamEntity en;
				en = new InputStreamEntity(fs, -1);
				
				if (request.containsHeader("Range")) {
					
					String range = request.getHeaders("Range")[0].getValue();
					Log.d(tag, "Found range=" + range);
					int ranges[] = getRanges(range, dp.content_length);
					
					Log.d(tag, "Found start byte=" + ranges[0] + ", endByte=" + ranges[1]);
					if (ranges[0] != -1) {
						
					}
				}
				
				response.setStatusCode(200);
				response.setHeader("Content-Type", contentType);
				response.setHeader("Content-Length", String.valueOf(dp.content_length));
			
				for (Header respHeader : response.getAllHeaders()) {
					Log.d(tag, "resp:" + respHeader.getName() + ": " + respHeader.getValue());
				}
				
				response.setEntity(en);
				
			} catch (Exception e) {
				Log.e(tag, "handlePlay() - " + e.toString(), e);
			}
			
			
		} else {
			Log.d(tag, "Not found id=" + id);
		}
		
		Log.d(tag, "handlePlay() - end");
		
	}

}
